﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Validation;
using Kingdee.BOS.Orm.DataEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;

namespace WSDZ.KM.ZH.ProduceReservationVerify6
{
    /// <summary>
    /// 生产补料单预留校验
    /// </summary>
    public class ProSupplementMatValidator : AbstractValidator
    {
        private static string btype = "生产补料单预留校验";
        public override void InitializeConfiguration(ValidateContext validateContext, Context ctx)
        {
            base.InitializeConfiguration(validateContext, ctx);
            if (validateContext.BusinessInfo != null)
            {
                EntityKey = validateContext.BusinessInfo.GetEntity(0).Key;
            }
        }

        public override void Validate(ExtendedDataEntity[] dataEntities, ValidateContext validateContext, Context ctx)
        {
            //if (validateContext.IgnoreWarning)
            //{
            //    return; // 警告已经被用户忽略，就不需要再次执行了       
            //}
            if (dataEntities == null || dataEntities.Length <= 0)
            {
                return;// 传入数据包为空
            }
            // 循环校验每一个数据包（一个数据包对应一张单据）
            foreach (var data in dataEntities)
            {
                string billno = data.BillNo.ToStringV1();
                try
                {
                    DynamicObjectCollection dynamicDatas = data.DataEntity["Entity"] as DynamicObjectCollection;
                    if (dynamicDatas == null|| dynamicDatas.Count<1)
                        continue;
                    int orgId = data.DataEntity["StockOrgId_Id"].ToStringV1().ToInt32V1();
                    var dList = dynamicDatas.Select(x => new { 
                        ser=x["Seq"].ToInt32V1(),
                        ppNo = x["PPBomBillNo"].ToStringV1(),//生产用料清单单号
                        ppEntyId = x["PPBomEntryId"].ToStringV1().ToInt32V1(),//生产用料清单明细ID
                        stockId = x["StockId_Id"].ToStringV1().ToInt32V1(),
                        cwId=x["StockLocId_Id"].ToStringV1().ToInt32V1(),
                        matId = x["MaterialId_Id"].ToStringV1(),
                        qty = x["ActualQty"].ToStringV1().ToDecimalV1()
                    }).ToList();
                    foreach (var pickObj in dList)
                    {


                        //实发数量大于预留数量， 超出部分 与可用库存比较  超出部分大于可用库存  拦截
                        string sql_yl = $@"select SUM(enty.FBASEQTY) from T_PLN_RESERVELINK main
left join T_PLN_RESERVELINKENTRY enty on main.FID=enty.FID 
left join T_PRD_PPBOMENTRY ppEnty on main.FDEMANDENTRYID =ppEnty.FENTRYID
left join T_PRD_PPBOM ppMain on ppEnty.FID=ppMain.FID
where main.FDEMANDBILLNO='{pickObj.ppNo}'
and main.FDEMANDENTRYID={pickObj.ppEntyId}
and main.FDEMANDFORMID='PRD_PPBOM'
and enty.FSUPPLYFORMID='STK_Inventory'
and enty.FSUPPLYORGID={orgId} 
and enty.FSTOCKID={pickObj.stockId} 
and enty.FMATERIALID={pickObj.matId}
and enty.FSTOCKLOCID={pickObj.cwId}";
                        decimal yl = DBUtils.ExecuteScalar<decimal>(Context, sql_yl, 0);
                        decimal overQty = pickObj.qty - yl;
                        if (overQty > 0)
                        {
                            string sql_jskc = $@"/*dialect*/ select ISNULL((select SUM(enty.FBASEQTY) 
from T_STK_INVENTORY enty
where enty.FSTOCKORGID={orgId} 
and enty.FSTOCKID={pickObj.stockId}
and enty.FMATERIALID={pickObj.matId}
and enty.FSTOCKLOCID={pickObj.cwId}),0)
- ISNULL((select SUM(enty.FBASEQTY) from T_PLN_RESERVELINKENTRY enty
where enty.FSUPPLYFORMID='STK_Inventory'
and enty.FSUPPLYORGID={orgId}
and enty.FSTOCKID={pickObj.stockId}
and enty.FMATERIALID={pickObj.matId}
and enty.FSTOCKLOCID={pickObj.cwId}),0)";
                            //                            decimal jskc = DBUtils.ExecuteScalar<decimal>(Context, $@"select SUM(FBASEQTY) from T_STK_INVENTORY
                            //where FSTOCKORGID={orgId} and FSTOCKID={pickObj.stockId} and FMATERIALID={pickObj.matId} and FSTOCKLOCID={pickObj.cwId}", 0);
                            decimal jskc = DBUtils.ExecuteScalar<decimal>(Context, sql_jskc, 0);
                            if (overQty > jskc)
                            {
                                validateContext.AddError(data, new ValidationErrorInfo(
                                                                        "FMaterialId",//出错的字段KEY，可以空
                                                                        data.DataEntity[0].ToString(),// 数据包内码，必填，后续操作会据此内码避开此数据包
                                                                        data.DataEntityIndex,
                                                                        data.RowIndex,
                                                                        "SaveVerify",//错误码
                                                                        $@"单号{billno}第{pickObj.ser}行预留量不足或者可用量不足,实发数量：{pickObj.qty};预留量：{yl}; 可用库存：{jskc}",
                                                                        "保存校验",
                                                                        ErrorLevel.FatalError
                                                                        ));
                            }
                        }




                        //                        //没有预留关系，并且没有可用库存的，不允许保存；
                        //                        {
                        //                            string sql = $@"select 1 from T_PLN_RESERVELINKENTRY 
                        //where FSUPPLYORGID={orgId} and FSTOCKID={pickObj.stockId} and FMATERIALID={pickObj.matId}";
                        //                            int scount = DBUtils.ExecuteScalar<int>(Context,sql,0);
                        //                            if (scount<=0)
                        //                            {
                        //                                //查询可用库存
                        //                                decimal jskc = DBUtils.ExecuteScalar<decimal>(Context,$@"select SUM(FBASEQTY) from T_STK_INVENTORY
                        //where FSTOCKORGID={orgId} and FSTOCKID={pickObj.stockId} and FMATERIALID={pickObj.matId}",0);
                        //                                if (jskc<=0)
                        //                                {
                        //                                    validateContext.AddError(data, new ValidationErrorInfo(
                        //                                                                           "FMaterialId",//出错的字段KEY，可以空
                        //                                                                           data.DataEntity[0].ToString(),// 数据包内码，必填，后续操作会据此内码避开此数据包
                        //                                                                           data.DataEntityIndex,
                        //                                                                           data.RowIndex,
                        //                                                                           "SaveVerify",//错误码
                        //                                                                           $@"第{pickObj.ser}行没有预留关系，并且没有可用库存的,不可保存!!!",
                        //                                                                           "保存校验",
                        //                                                                           ErrorLevel.FatalError
                        //                                                                           ));
                        //                                    break;
                        //                                }
                        //                            }
                        //                        }
                        //                        //如果存在预留数量，但是预留数量不是即时库存的，也不允许保存
                        //                        {
                        //                            //查询是否存在预留数量
                        //                            string sql1 = $@"select sum(FBASEQTY) from T_PLN_RESERVELINKENTRY 
                        //where FSUPPLYORGID={orgId} and FSTOCKID={pickObj.stockId} and FMATERIALID={pickObj.matId}";
                        //                            decimal ylQty1 = DBUtils.ExecuteScalar<decimal>(Context, sql1, 0);
                        //                            if (ylQty1 > 0)
                        //                            {
                        //                                //查询是否存在即时库存的预留数量
                        //                                string sql = $@"select sum(FBASEQTY) from T_PLN_RESERVELINKENTRY 
                        //where FSUPPLYFORMID='STK_Inventory' and  FSUPPLYORGID={orgId} and FSTOCKID={pickObj.stockId} and FMATERIALID={pickObj.matId}";
                        //                                decimal ylQty = DBUtils.ExecuteScalar<decimal>(Context, sql, 0);
                        //                                if (ylQty <= 0)
                        //                                {
                        //                                    validateContext.AddError(data, new ValidationErrorInfo(
                        //                                                                            "FMaterialId",//出错的字段KEY，可以空
                        //                                                                            data.DataEntity[0].ToString(),// 数据包内码，必填，后续操作会据此内码避开此数据包
                        //                                                                            data.DataEntityIndex,
                        //                                                                            data.RowIndex,
                        //                                                                            "SaveVerify",//错误码
                        //                                                                            $@"第{pickObj.ser}行预留数量不足,不可保存!!!",
                        //                                                                            "保存校验",
                        //                                                                            ErrorLevel.FatalError
                        //                                                                            ));
                        //                                    break;
                        //                                }
                        //                            }

                        //                        }
                    }
                    

            
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }


        }
  

    }

}
